package com.njlime.core.sdk.wechat;

import com.njlime.cms.entities.MaterialsNews;
import com.njlime.cms.entities.MaterialsVoice;
import com.njlime.cms.service.sys.MaterialNewsService;
import com.njlime.cms.service.sys.MaterialVoiceService;
import com.njlime.core.sdk.wechat.msg.WeChatArticle;
import com.njlime.core.sdk.wechat.msg.WeChatMsgUtil;
import com.njlime.core.sdk.wechat.msg.WeChatMusic;
import com.njlime.core.sdk.wechat.msg.response.WeChatMusicMsg;
import com.njlime.core.sdk.wechat.msg.response.WeChatNewsMsg;
import com.njlime.core.sdk.wechat.msg.response.WeChatTextMsg;
import com.njlime.member.service.app.AppMemberService;
import com.njlime.sys.service.app.AppWxConfigService;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


public class CoreService {

	static Logger logger = Logger.getLogger(CoreService.class);
	/**
	 * 处理微信发来的请求
	 * 
	 * @param request
	 * @return
	 */
	public static String processRequest(HttpServletRequest request, AppWxConfigService wxConfigService, AppMemberService appMemberService,
           MaterialVoiceService materialVoiceService, MaterialNewsService materialNewsService) {
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "";
			// xml请求解析
			Map<String, String> requestMap = WeChatMsgUtil.parseXml(request);

			System.out.println("processRequest and request is " + requestMap);
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			// 消息类型
			String content = requestMap.get("Content");

			// 回复文本消息
			WeChatTextMsg respMsg = new WeChatTextMsg();
			respMsg.setToUserName(fromUserName);
			respMsg.setFromUserName(toUserName);
			respMsg.setCreateTime(new Date().getTime());
			respMsg.setMsgType(WeChatMsgUtil.RESP_MESSAGE_TYPE_TEXT);
			respMsg.setFuncFlag(0);

			// 文本消息
			if (msgType.equals(WeChatMsgUtil.REQ_MESSAGE_TYPE_TEXT)) {

                respMsg.setContent(respContent);
                respMessage = WeChatMsgUtil.textMessageToXml(respMsg);
			}
			// 图片消息
			else if (msgType.equals(WeChatMsgUtil.REQ_MESSAGE_TYPE_IMAGE)) {
			//	respContent= msgType;
			}
			// 地理位置消息
			else if (msgType.equals(WeChatMsgUtil.REQ_MESSAGE_TYPE_LOCATION)) {
			//	respContent= msgType;
			}
			// 链接消息
			else if (msgType.equals(WeChatMsgUtil.REQ_MESSAGE_TYPE_LINK)) {
			//	respContent= msgType;
			}
			// 音频消息
			else if (msgType.equals(WeChatMsgUtil.REQ_MESSAGE_TYPE_VOICE)) {
			//	respContent= msgType;
			}
			// 事件推送
			else if (msgType.equals(WeChatMsgUtil.REQ_MESSAGE_TYPE_EVENT)) {
				// 事件类型
				String eventType = requestMap.get("Event");

				// 订阅
				if (eventType.equals(WeChatMsgUtil.EVENT_TYPE_SUBSCRIBE)) {
					respContent = "谢谢您的关注！";
				}
				// 取消订阅
				else if (eventType.equals(WeChatMsgUtil.EVENT_TYPE_UNSUBSCRIBE)) {
					// 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
				}
				// 自定义菜单点击事件
				else if (eventType.equals(WeChatMsgUtil.EVENT_TYPE_CLICK)) {
					// 事件KEY值，与创建自定义菜单时指定的KEY值对应
					String eventKey = requestMap.get("EventKey");
					String event_type = eventKey.split("\\|")[0];
                    Integer event_unit = Integer.valueOf(eventKey.split("\\|")[1]);
                    Integer event_id = Integer.valueOf(eventKey.split("\\|")[2]);

                    if("news".equals(event_type)){
                        MaterialsNews materialsNews = materialNewsService.get(event_id,event_unit);
                        WeChatNewsMsg weChatNewsMsg = new WeChatNewsMsg();
                        weChatNewsMsg.setToUserName(fromUserName);
                        weChatNewsMsg.setFromUserName(toUserName);
                        weChatNewsMsg.setCreateTime(new Date().getTime());
                        weChatNewsMsg.setMsgType(WeChatMsgUtil.RESP_MESSAGE_TYPE_NEWS);
                        weChatNewsMsg.setFuncFlag(0);
                        List<WeChatArticle> articles = new ArrayList<>();
                        WeChatArticle weChatArticle = new WeChatArticle();
                        weChatArticle.setTitle(materialsNews.getTitle());
                        weChatArticle.setDescription(materialsNews.getAbstract_info());
                        weChatArticle.setPicUrl(materialsNews.getImage_path1());
                        String url = request.getScheme() + "://" + request.getServerName() + request.getContextPath()
                                + "/app/page?pv=material_detail&id="+ event_id + "&unit_id=" + event_unit;
                        weChatArticle.setUrl(url);
                        articles.add(weChatArticle);
                        weChatNewsMsg.setArticleCount(1);
                        weChatNewsMsg.setArticles(articles);
                        respMessage = WeChatMsgUtil.newsMessageToXml(weChatNewsMsg);
                        logger.debug("respMessage:" + respMessage);
                    }else if("voice".equals(event_type)){
                        MaterialsVoice materialsVoice = materialVoiceService.get(event_id,event_unit);
                        WeChatMusicMsg weChatMusicMsg = new WeChatMusicMsg();
                        weChatMusicMsg.setToUserName(fromUserName);
                        weChatMusicMsg.setFromUserName(toUserName);
                        weChatMusicMsg.setCreateTime(new Date().getTime());
                        weChatMusicMsg.setMsgType(WeChatMsgUtil.RESP_MESSAGE_TYPE_MUSIC);
                        weChatMusicMsg.setFuncFlag(0);
                        WeChatMusic weChatMusic = new WeChatMusic();
                        weChatMusic.setTitle(materialsVoice.getTitle());
                        weChatMusic.setDescription(materialsVoice.getTitle());
                        weChatMusic.setMusicUrl(materialsVoice.getVoice_path().replace("&","&amp;"));
                        weChatMusic.setHQMusicUrl(materialsVoice.getVoice_path().replace("&","&amp;"));
                        weChatMusicMsg.setMusic(weChatMusic);
                        respMessage = WeChatMsgUtil.musicMessageToXml(weChatMusicMsg);
                        logger.debug("respMessage:" + respMessage);
                    }
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return respMessage;
	}

	public static String processRequest2(HttpServletRequest request,AppWxConfigService wxConfigService) {
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "";
			// 发送方帐号（open_id）
			String fromUserName = request.getParameter("FromUserName");
			// 公众帐号
			String toUserName = request.getParameter("ToUserName");
			// 消息
			String content = request.getParameter("Content");
            respMessage = "";
		} catch (Exception e) {
			e.printStackTrace();
		}

		return respMessage;
	}

}